package com.lin.csdn.controller;

import com.lin.csdn.service.impl.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    /**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     *
     * 0：查找用户个人信息 SeekInformation
     * 1：修改邮箱数据 UpdateEmail
     * 2：修改用户名 UpdateUserName
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //建立功能代表的code调用
        String SeekInformation="0";
        String UpdateEmail="1";
        String UpdateUserName="2";
        //获取req数据
        String code=req.getParameter("code");

        List<Object> data;
        UserService userService=new UserService();
        PrintWriter writer = resp.getWriter(); //响应流
        JSONArray array=new JSONArray();

        //根据需求调用各自的方法
        if(code.equals(SeekInformation)){
            String userName=req.getParameter("userName");
            data=userService.searchInformation(userName);
            for(int i=0;i<data.size();i++){
                JSONObject object=new JSONObject();
                object.put("email",data.get(i));
                i++;
                object.put("name", data.get(i));
                array.put(object);
            }
            writer.print(array);
        }
        else if(code.equals(UpdateEmail)){
            String userName=req.getParameter("userName");
            String email=req.getParameter("email");
            userService.updateEmail(userName,email);
            JSONObject object=new JSONObject();
            object.put("result","200");
            writer.print(object);
        }
        else if(code.equals(UpdateUserName)){
            String userName=req.getParameter("userName");
            String name=req.getParameter("name");
            userService.updateName(userName,name);
            JSONObject object=new JSONObject();
            object.put("result","200");
            writer.print(object);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
